<script setup lang="ts">
import { getWalletSummaryAPI, getWalletTransactionsAPI } from "~/api/wallet";
import WalletRecharge from "~/components/dialog/WalletRecharge.vue";

useSeoMeta({
  title: "企业账户 - 技能猴子",
  ogTitle: "企业账户 - 技能猴子",
  description: "技能猴子，找技能服务，我喜欢和技能人才直接聊",
  ogDescription: "技能猴子，找技能服务，我喜欢和技能人才直接聊",
});

onMounted(() => {
  getWalletSummary();
  getTransactionsList();
});

// 钱包概览数据
const walletSummary = ref({
  availableBalance: 0,
  totalRecharge: 0,
  frozenAmount: 0,
  totalPaid: 0
});

// 获取钱包概览
const getWalletSummary = async () => {
  try {
    const { code, data } = await getWalletSummaryAPI({});
    if (code === 200) {
      // 兼容接口返回为null或字段缺失的情况
      const safe = data && typeof data === 'object' ? data : {};
      walletSummary.value = {
        availableBalance: Number(safe.availableBalance ?? 0),
        totalRecharge: Number(safe.totalRecharge ?? 0),
        frozenAmount: Number(safe.frozenAmount ?? 0),
        totalPaid: Number(safe.totalPaid ?? 0)
      };
    }
  } catch (e) {
    console.log(e);
  }
};

// 流水记录数据
const transactionsList = ref([]);
const total = ref(0);
const pageNum = ref(1);
const pageSize = ref(10);
const loading = ref(false);

// 获取流水记录
const getTransactionsList = async () => {
  loading.value = true;
  try {
    const { code, data } = await getWalletTransactionsAPI({
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      orderByColumn: 'createTime',
      isAsc: 'desc'
    });
    if (code === 200) {
      transactionsList.value = data.rows || [];
      total.value = data.total || 0;
    }
  } catch (e) {
    console.log(e);
  } finally {
    loading.value = false;
  }
};

// 分页切换
const currentChange = (page) => {
  pageNum.value = page;
  getTransactionsList();
};

// 交易类型格式化
const transactionTypeFormatter = (row) => {
  switch (row.transactionType) {
    case 1:
      return "充值";
    case 2:
      return "消费";
    case 3:
      return "退款";
    case 4:
      return "提现";
    default:
      return "其他";
  }
};

// 交易状态格式化
const tradeStatusFormatter = (row) => {
  switch (row.tradeStatus) {
    case 0:
      return "待处理";
    case 1:
      return "成功";
    case 2:
      return "失败";
    case 3:
      return "已取消";
    default:
      return "未知";
  }
};

// 金额格式化
const amountFormatter = (row) => {
  const amount = parseFloat(row.amount || 0);
  return row.transactionType === 1 || row.transactionType === 3 
    ? `+${amount.toFixed(2)}` 
    : `-${amount.toFixed(2)}`;
};

// 金额颜色类
const getAmountClass = (row) => {
  return row.transactionType === 1 || row.transactionType === 3 
    ? 'amount-positive' 
    : 'amount-negative';
};

// 充值弹框
const rechargeVisible = ref(false);
const openRecharge = () => {
  rechargeVisible.value = true;
};
const afterRechargeSuccess = () => {
  // 刷新概览与流水
  getWalletSummary();
  getTransactionsList();
};

// 金额安全格式化
const formatAmount = (v) => {
  const num = Number(v);
  return isNaN(num) ? '0.00' : num.toFixed(2);
};
</script>

<template>
  <BaseHeaderMenuWhite bg-color="white" />
  <div class="company-account">
    <h4 class="page-title">企业账户</h4>
    
    <!-- 钱包概览 -->
    <div class="wallet-summary">
      <div class="summary-card">
        <div class="card-item">
          <div class="card-value">¥{{ formatAmount(walletSummary?.availableBalance) }}</div>
          <div class="card-label">可用余额</div>
        </div>
        <div class="card-item">
          <div class="card-value">{{ formatAmount(walletSummary?.totalRecharge) }}</div>
          <div class="card-label">累计充值</div>
        </div>
<!--        <div class="card-item">-->
<!--          <div class="card-value">{{ formatAmount(walletSummary?.frozenAmount) }}</div>-->
<!--          <div class="card-label">已冻结</div>-->
<!--        </div>-->
        <div class="card-item">
          <div class="card-value">{{ formatAmount(walletSummary?.totalPaid) }}</div>
          <div class="card-label">已支付</div>
        </div>
      </div>
      <div class="action-buttons">
        <el-button type="primary" class="charge-btn" @click="openRecharge">充值</el-button>
      </div>
    </div>

    <!-- 流水记录 -->
    <div class="transactions-list">
      <p class="header">
        <span class="size">流水记录（{{ total }}）</span>
      </p>
      <div class="table">
        <el-table
          :data="transactionsList"
          style="width: 100%"
          v-loading="loading"
          :header-cell-style="{
            background: '#F5F7FA',
            height: '54px',
            color: '#191E28',
          }"
          :cell-style="{ height: '70px' }"
        >
          <el-table-column
            type="index"
            label="序号"
            width="70"
            align="center"
          ></el-table-column>
          <el-table-column label="交易类型" prop="transactionType" width="120">
            <template #default="scope">
              <span>{{ transactionTypeFormatter(scope.row) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="金额" prop="amount" width="150">
            <template #default="scope">
              <span :class="getAmountClass(scope.row)">
                {{ amountFormatter(scope.row) }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="交易状态" prop="tradeStatus" width="120">
            <template #default="scope">
              <span>{{ tradeStatusFormatter(scope.row) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="交易时间" prop="tradeTime"></el-table-column>
          <el-table-column label="备注" prop="remark" show-overflow-tooltip></el-table-column>
        </el-table>
      </div>
      <div class="pagination">
        <el-pagination
          layout="prev, pager, next"
          :page-size="pageSize"
          :total="total"
          @current-change="currentChange"
        />
      </div>
    </div>
  </div>
  <BaseFooter />
  <!-- 充值弹框 -->
  <WalletRecharge v-if="rechargeVisible" @close="rechargeVisible=false" @success="afterRechargeSuccess" />
</template>

<style scoped lang="scss">
.company-account {
  padding-top: 80px;
  width: 1100px;
  margin: 0 auto;
  padding-bottom: 36px;
}

.page-title {
  color: #191e28;
  font-size: 20px;
  padding-top: 32px;
  padding-bottom: 16px;
}

.wallet-summary {
  background: #ffffff;
  box-shadow: 0px 0px 16px 0px rgba(11, 13, 18, 0.06);
  border-radius: 16px;
  border: 1px solid rgba(25, 30, 40, 0.08);
  padding: 24px;
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;

  .summary-card {
    display: flex;
    gap: 60px;

    .card-item {
      text-align: center;

      .card-value {
        font-size: 28px;
        font-weight: bold;
        color: #019a81;
        margin-bottom: 8px;
      }

      .card-label {
        font-size: 14px;
        color: #666;
      }
    }
  }

  .action-buttons {
    .charge-btn {
      background: #019a81;
      border-color: #019a81;
      padding: 12px 24px;
      font-size: 16px;
    }
  }
}

.transactions-list {
  background: #ffffff;
  box-shadow: 0px 0px 16px 0px rgba(11, 13, 18, 0.06);
  border-radius: 16px;
  border: 1px solid rgba(25, 30, 40, 0.08);
  padding: 20px 24px;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    margin-bottom: 20px;

    .size {
      flex: 1;
      color: #191e28;
      font-size: 16px;
      font-weight: bold;
    }
  }

  .table {
    border: 1px solid #e5e7eb;
    border-radius: 12px;
    overflow: hidden;
  }

  .amount-positive {
    color: #019a81;
    font-weight: bold;
  }

  .amount-negative {
    color: #ff4f4f;
    font-weight: bold;
  }
}

.pagination {
  display: flex;
  align-items: center;
  justify-content: center;
  padding-top: 20px;
}
</style>

<style lang="scss">
.el-pagination button:disabled {
  background: none;
}
.el-pagination button.is-first {
  margin-right: 6px;
}
.el-pagination button.is-last {
  background: none;
  &:hover {
    font-weight: bold;
    color: #191e28;
  }
}
.el-pager li {
  background: none;
  width: 36px;
  height: 36px;
  margin-right: 6px;
  &:hover {
    font-weight: bold;
    color: #191e28;
  }
}
.el-pager li.is-active {
  background: #fff;
  box-shadow: 0 0 16px 0 rgba(11, 13, 18, 0.06);
  border-radius: 8px;
  border: 1px solid rgba(25, 30, 40, 0.08);
  color: #191e28;
}
</style>